<?php
namespace Api;
use Kuyuan\WqCore\api\Api;
use Kuyuan\WqCore\util\DB;
use Kuyuan\WqCore\util\Util;
use Yansongda\Pay\Exceptions\Exception;
use Yansongda\Pay\Pay;

/**
 * 提现
 * Class Deposit
 * @package Api
 */
class Deposit extends Api
{
    private $Deposit = null;
    public function __construct()
    {
        parent::__construct();
        $this->Deposit = new \Controller\Deposit();
    }

    /**
     * 提现
     */
    public function deposit()
    {
        Util::appointPost();
        DB::begin();
        try {
            $_deposit_money = $this->_gpc["deposit_money"];
            $Member = $this->newController("Member");
            // 提现至目标 account = 系统账户余额 wx = 微信钱包
            $_target = 'account';
            // 验证用户余额
            if($_deposit_money > $Member->finance()) {
                throw new \PDOException("余额不足",700);
            }

            // 最低提现金额验证
            $SettingFinance = $this->newController("SettingFinance");
            $_setting_finance = $SettingFinance->find();
            if($_deposit_money < $_setting_finance["low_deposit"]) {
                throw new \PDOException(
                    "提现金额不能低于".sprintf("%.2f",$_setting_finance["low_deposit"])."元",
                    701
                );
            }

            // 减去用户余额
            $Member->financeHandle($_deposit_money,false);

            // 创建提现记录
            $_order_id = $this->Deposit->add(array("money"=>$_deposit_money));

            // 判断是否直接到用户微信钱包
            if($_setting_finance["deposit_check"] === 0 || $_deposit_money >= $_setting_finance["deposit_check"]){
                // 审核不直接到账
            } else {
                // 调用微信支付，直接到账
                $_target = "wx";
                $Setting = $this->newController("Setting");
                $_setting = $Setting->find();
                $_pay_config = \Kuyuan\WqCore\wx\Pay::config();
                \Kuyuan\WqCore\wx\Pay::getCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                try{
                    $_pay_result = Pay::wechat($_pay_config)->transfer(array(
                        "partner_trade_no"=>$_order_id,
                        "openid" => $Member->uidToOpenid(),
                        'check_name' => 'NO_CHECK',
                        'amount' => $_deposit_money * 100,
                        'desc' => $_setting_finance["remark"] ? $_setting_finance["remark"] : $_setting["app_name"]."提现成功",
                    ));
                    \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                    if($_pay_result->return_code != "SUCCESS" || $_pay_result->result_code != "SUCCESS") {
                        throw new \PDOException("未知错误",708);
                    }
                    $this->Deposit->edit(array("status"=>1),$_order_id);
                } catch (Exception $e) {
                    \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                    $_message = explode(':',$e->getMessage());
                    throw new \PDOException(end($_message),700);
                }
            }
            DB::commit();
            Util::returns(array("code"=>0,"data"=>$_target));
        } catch (\PDOException $e) {
            DB::back();
            $_result = array("code"=>$e->getCode(),"err_msg"=>$e->getMessage());
            Util::returns($_result);
        }
    }

    /**
     * 后台提现
     */
    public function manageDeposit()
    {
        Util::appointPost();
        DB::begin();
        try{
            $_deposit = $this->Deposit->find($this->_gpc["deposit_id"]);
            if($_deposit["status"] != 0) {
                throw new \PDOException("已处理的提现",108);
            }
            $_pay_config = \Kuyuan\WqCore\wx\Pay::config(false);
            \Kuyuan\WqCore\wx\Pay::getCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
            try{
                $Member = $this->newController("Member");
                $SettingFinance = $this->newController("SettingFinance");
                $_setting_finance = $SettingFinance->find();
                $Setting = $this->newController("Setting");
                $_setting = $Setting->find();
                $_pay_result = Pay::wechat($_pay_config)->transfer(array(
                    "partner_trade_no"=>$_deposit["order_id"],
                    "openid" => $Member->uidToOpenid($_deposit["uid"]),
                    'check_name' => 'NO_CHECK',
                    'amount' => $_deposit["money"] * 100,
                    'desc' => $_setting_finance["remark"] ? $_setting_finance["remark"] : $_setting["app_name"]."提现成功",
                ));
                \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                if($_pay_result->return_code != "SUCCESS" || $_pay_result->result_code != "SUCCESS") {
                    throw new \PDOException("未知错误",708);
                }
            }catch (Exception $e) {
                \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                $_message = explode(':',$e->getMessage());
                throw new \PDOException(end($_message),700);
            }
            $this->Deposit->edit(array("status"=>1),$_deposit["order_id"]);
            DB::commit();
            Util::returns(array("code"=>0));
        }catch (\PDOException $e) {
            DB::back();
            Util::returns(array("code"=>$e->getCode(),"err_msg"=>$e->getMessage()));
        }
    }

    /**
     * 获取用户提现列表
     */
    public function getUserList()
    {
        Util::appointGet();
        $_list = $this->Deposit->getUserList($this->_gpc["limit"]);
        if($_list) {
            $_result = array("code"=>0,"data"=>$_list);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 获取系统提现列表
     */
    public function getList()
    {
        Util::appointGet();
        $_list = $this->Deposit->getList($this->_gpc["limit"],$this->_gpc["status"]);
        if($_list) {
            $_result = array("code"=>0,"data"=>$_list);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 获取系统提现总数
     */
    public function getTotal()
    {
        Util::appointGet();
        Util::returns(array("code"=>0,"data"=>$this->Deposit->getTotal($this->_gpc["status"])));
    }

    /**
     * 后台管理拒绝提现
     */
    public function refuse()
    {
        Util::appointPost();
        DB::begin();
        try{
            $_deposit = $this->Deposit->find($this->_gpc["deposit_id"]);
            $this->Deposit->edit(array("status"=>2),$_deposit["order_id"]);
            $Member = $this->newController("Member");
            $Member->financeHandle($_deposit["money"],true,$_deposit["uid"]);
            DB::commit();
            Util::returns(array("code"=>0));
        }catch (\PDOException $e) {
            DB::back();
            Util::returns(array("code"=>103));
        }
    }
}